import react, { useContext, useEffect, useState } from 'react'
import './index.css'

const LinkAnimation: react.FC<LinkAnimationProps> = (props: LinkAnimationProps) => {
    console.log(props);

    const [state] = useState({
        children: props.children,//插槽
    })
    const [height, setHeight] = useState(0)
    const [style] = useState(props.style)
    const { children } = state
    const number = props.number
    const name = props.name
    useEffect(() => {
        // 因为是子元素是绝对定位父盒子没有高度所以这里要计算出子元素所有的高度总和
        const link = document.getElementById('link-animation' + name)
        // 拿到所有子元素
        const linkLenght = link?.children.length as number
        // 初始化高度
        let heights: number = 0
        // 初始化宽度
        let widths: number = 0
        // 循环拿到每个子元素的高
        let arr = []

        for (let i = 0; i < linkLenght; i++) {
            heights += link?.children[i].clientHeight as number
            arr.push(link?.children[i].clientWidth as number)
            widths = Math.max(...arr)

        }
        setHeight(heights)

        // 判断动画类型
        switch (props.type) {
            case 'top':
                link?.style.setProperty('--toplength', `-${number ? number : heights}px`)
                break;
            case 'left':
                link?.style.setProperty('--Leftlength', `-${number ? number :widths}px`)
                break;
            case 'bottom':
                link?.style.setProperty('--toplength', `${number ? number :heights}px`)
                break;
            case 'right':
                link?.style.setProperty('--Leftlength', `${number ? number :widths}px`)
                break;
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [height])

    return (
        <div style={{ position: 'relative', height: height + 'px', ...style }}>
            <div id={'link-animation' + name} className={props.LinkIf ? '' : props.type} style={{ opacity: props.LinkIf ? '1' : '0', left: '0', top: '0', bottom: '0', right: '0', zIndex: '-1', transition: 'all 1s', position: 'absolute' }}>{children}</div>
        </div>
    )
}

export default LinkAnimation
